package com.senyint.sys.utils.task;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;

/**
 * spring 动态任务管理工具
 * {@code SpringTaskUtils}类<p>
 * @author NaiFei Wang, wangnaifei@senyint.com
 * @date 2016年3月30日 下午3:45:20
 * @version 1.0
 * @since  jdk1.7+
 */
public class SpringTaskUtils {

	public static final Logger LOGGER = LoggerFactory.getLogger(SpringTaskUtils.class);
	private final static int POOL_SIZE = 64;

	private final ConcurrentTaskScheduler scheduler = new ConcurrentTaskScheduler(Executors.newScheduledThreadPool(POOL_SIZE));

	/**
	 * 启动一个计划任务.
	 * 
	 * @param task 当前进行的任务.
	 */
	public ScheduledFuture<?> start(Runnable task, String exprission) {
		return scheduler.schedule(task, new CronTrigger(exprission));
	}

	/**
	 * 停止一个计划任务.
	 * 
	 * @param taskId 任务编号.
	 */
	public void stop(ScheduledFuture<?> scheduledFuture) {
		if (!scheduledFuture.isCancelled()) {
			/** false 表示当前任务若正在执行，则待其执行结束，再结束此任务. */
			scheduledFuture.cancel(false);
		}
	}

	/**
	 * 仅执行一次.
	 * 
	 * @param task 所要执行任务.
	 */
	public void onlyOneTime(Runnable task) {
		scheduler.execute(task, 2000);
	}

	/**
	 * 销毁线程池中的任务.
	 */
	public void destrory() {
		LOGGER.info("正在终止自动任务的线程池资源.");
		ScheduledExecutorService scheduledExecutor = (ScheduledExecutorService) scheduler.getConcurrentExecutor();
		scheduledExecutor.shutdownNow();
	}
}
